package red.yancloud.www.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import red.yancloud.www.R;
import red.yancloud.www.common.Constants;
import red.yancloud.www.manager.AppManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

/**
 * @author 55345364
 * @date 2017/7/5.
 */
public final class AppUtils {

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null) {
            info = new PackageInfo();
        }
        return info;
    }


    /**
     * 获取版本名
     * @return
     */
    public static String getPackageName(){
        PackageInfo packageInfo = Utils.getPackageInfo();
        if(null != packageInfo){
            return packageInfo.packageName;
        }
        return "";
    }


    /**
     * 获取版本号
     * @return
     */
    public static int getAppVersionCode(){
        PackageInfo packageInfo = Utils.getPackageInfo();
        if(null != packageInfo){
            return packageInfo.versionCode;
        }
        return 1;
    }


    /**
     * 获取版本名
     *
     * @return 当前应用的版本名
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }


    /**
     * @Author：风不会停息 on 2019/1/11 11:45
     * @param name
     * @Description：获取渠道名称
     * @Change：
     */
    public static String getChannel(String name) {
        ApplicationInfo info;
        try {
            info = Utils.getAppContext().getPackageManager().getApplicationInfo(
                    getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }


    /**
     * @Author：风不会停息 on 2019/2/15 14:29
     * E_Mail：yh131412hys@163.com
     * @param context
     * @Description：获取uuid
     * @Change：
     * @Version：V1.0
     */
    @SuppressLint("MissingPermission")
    public static String getMyUUID(Context context) {

        String uniqueId = "";
//        PermissionsCheck permissionsCheck = new PermissionsCheck(context);
//        if(permissionsCheck.lacksPermissions(PermissionsActivity.PERMISSIONS)){
//            if(context != null && context instanceof Activity){
//                PermissionsActivity.startActivityForResults((Activity)context, Constants.UserPermission.REQUEST_PERMISSIONS_CODE,PermissionsActivity.PERMISSIONS);
//            }
//        }else{
//
//
//        }

        final TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = ""
                + android.provider.Settings.Secure.getString(
                context.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        UUID deviceUuid = new UUID(androidId.hashCode(),
                ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        uniqueId = deviceUuid.toString();

        return uniqueId;
    }


    /**
     * 获取网络访问签名
     * @return
     */
    public static String getSign(String interfaceName){
//        'DEV_KEY'=>'yananhongyun',
//	'DEV_SECRET'=>'cyhaywjgzdyh',
//        $signstr = md5(I('ac') .'#'.$this->dev_key.'#'.I('timestamp').'#'.$this->dev_secret);
//        return MD5Utils.string2MD5(AppUtils.getPackageName() + TimeFormatUtil.getCurrentDateTimeSeconds()  + PhoneUtils.getUUID() + Constants.KEY_SIGN);
        return MD5Utils.string2MD5(interfaceName + "#" + Constants.DEV_KEY + "#" + TimeFormatUtil.getCurrentDateTimeSeconds() + "#" + Constants.DEV_SECRET);
    }


    /**
     * 获取拥有权限
     *
     * @param context
     * @param permission
     * @return
     */
    public static String getAuthorityFromPermission(Context context, String permission) {
        if (permission == null) {
            return null;
        }
        List<PackageInfo> packs = context.getPackageManager()
                .getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission)) {
                            return provider.authority;
                        }
                        if (permission.equals(provider.writePermission)) {
                            return provider.authority;
                        }
                    }
                }
            }
        }
        return null;
    }


    public static String parseDpi(int dpi){
        String flag = "xhdpi";
        if(480 <= dpi && 720 > dpi){
            flag =  "hdpi";
        }else if(720 <= dpi && 1080 > dpi){
            flag = "xhdpi";
        }else if(1080 <= dpi){
            flag = "xxhdpi";
        }
        return flag;
    }


    public static boolean isInstallApp(Context context,String packageName){
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if(null != pinfo){
            for (int i = 0; i < pinfo.size(); i++) {
                String name = pinfo.get(i).packageName;
                Log.e("","-----"+pinfo.size()+"----------<<" + name);
                if(name.equals(packageName)){
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 系统分享功能
     *
     * @param context
     * @param msgTitle
     *            分享标题
     * @param msgText
     *            分享内容
     * @param imgPath
     *            照片路径
     */
    public static void shareBook(Context context, String msgTitle,
                                 String msgText, String imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (imgPath == null || imgPath.equals("")) {
            intent.setType("text/plain"); // 纯文本
        } else {
            File f = new File(imgPath);
            if (f != null && f.exists() && f.isFile()) {
                intent.setType("image/png");
                Uri u = Uri.fromFile(f);
                intent.putExtra(Intent.EXTRA_STREAM, u);
            }
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgTitle + msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, "分享"));
    }


    /**
     * @Author：风不会停息 on 2019/2/13 11:13
     * E_Mail：yh131412hys@163.com
     * @param context
     * @param vurl
     * @param vimg
     * @param vintro
     * @param varticlename
     * @Description：自定义分享功能
     * @Change：
     * @Version：V1.0
     */
    public static void customShareBook(Context context, final String vurl, final String vimg,
                                       final String vintro ,final String varticlename) {

//		Intent intent = new Intent(context, CustomShareActivity.class);
//		intent.putExtra("vurl", vurl);
//		intent.putExtra("vimg", vimg);
//		intent.putExtra("vintro", vintro);
//		intent.putExtra("varticlename", varticlename);
//		context.startActivity(intent);
//
//		if(context instanceof Activity){
//			Activity activity = (Activity) context;
//			activity.overridePendingTransition (R.anim.bottom_menu_in,0);
//		}
//        new ShareDialog(context,vurl,vimg,vintro,varticlename).show();
    }


//    /**
//     * 下载书籍
//     *
//     * @param context
//     * @param articleId  书id
//     * @param articleName  书名
//     * @param type  下载章节类型
//     */
//    public static void downLoadChapter(Context context, String articleId,
//                                       String articleName,int type) {
//        Intent intent = new Intent(context, DownLoadService.class);
//        intent.putExtra("down_articleid", articleId);
//        intent.putExtra("down_articlename", articleName);
//        intent.putExtra("down_type", type);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startService(intent);
//    }


    /**
     * 更新apk文件检测
     * @param versionName
     * @return
     */
    public static boolean appFileCheck(String versionName){
        String apkName = "OSShuHaiApp_" + versionName + ".apk";
        apkName = getPackageName() + ".apk";
        String savePath = "";
        String apkFilePath = "";
        String storageState = Environment.getExternalStorageState();
        if(!storageState.equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
        savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OSShuHai/Update/";
        apkFilePath = savePath + apkName;
        return new File(apkFilePath).exists();
    }

//    /**
//     * 缓存章节
//     * @param context
//     * @param articleId
//     * @param chapterId
//     * @param chapterOder
//     */
//    public static void cacheChapter(Context context,String articleId,String chapterId,String chapterOder){
//        Intent intent = new Intent(context, CacheChapterService.class);
//        intent.putExtra("cache_articleid", articleId);
//        intent.putExtra("cache_chap_name", chapterId);
//        intent.putExtra("cache_chap_order", chapterOder);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startService(intent);
//    }
//
//    /**
//     * 点击一次退出系统
//     * @param context
//     */
//    public static void ExitFirst(final Context context){
//        stopService(context,DownLoadService.class);
//        stopService(context,VersionUpdateService.class);
//        AppUtils.stopService(context,CacheChapterService.class);
//        AppManager.getAppManager().AppExit(context);
//    }

    /**
     * 停止后台服务
     * @param context
     */
    public static void stopService(Context context, Class<?> cls){
        Intent intent = new Intent(context, cls);
        context.stopService(intent);
    }

    /**
     * 获取assets目录下的json文件数据
     * */
    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 根据图片名称获取图片的资源id的方法
     * @param imageName
     * @return
     */
    public static int getResource(String imageName,Context mContext) {
        return mContext.getResources().getIdentifier(imageName, "mipmap", mContext.getPackageName());
    }

    /**
     * 根据图片名称获取图片的资源id的方法
     * @param name
     * @return
     */
    public static int getResourceId(String name) {
        try {
            // 根据图片资源的文件名获得Field对象
            Field field = R.mipmap.class.getField(name);
            // 取得并返回资源ID
            return Integer.parseInt(field.get(null).toString());
        } catch (Exception e) {}
        return 0;
    }

    private static long exitTime = 0;

    /**
     * 点击两次退出系统
     * @param cont
     */
    public static void Exit(final Context cont){
        if((System.currentTimeMillis() - exitTime) > 2000){
            ToastUtils.showToast(R.string.press_again_to_exit);
            exitTime = System.currentTimeMillis();
        }else{
//            AppUtils.stopService(cont, DownLoadService.class);
//            AppUtils.stopService(cont, VersionUpdateService.class);
//            AppUtils.stopService(cont, CacheChapterService.class);
            AppManager.getAppManager().AppExit(cont);
        }
    }

    /**
     * 关闭软件盘
     */
    public static void closeInoutDecorView(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getWindow().peekDecorView().getWindowToken(), 0);
    }

    public static void openBrowser(Context context,String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            ToastUtils.showToast("链接错误或无浏览器");
        }
    }
}
